#!/usr/bin/python
# -*- encoding: utf-8 -*-

"""
@File:      tc_nettle_nettle_func_002.py
@Time:      2024/04/08 14:51:50
@Author:    zhixin
@Version:   1.0
@Contact:   zx01468051@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    zhixin
"""

from common.basetest import LocalTest
import re

class Test(LocalTest):
    """
    See tc_nettle_nettle_func_002.yaml for details

    :avocado: tags=P2,noarch,local,fix
    """
    PARAM_DIC = {"pkg_name": "nettle nettle-devel gcc"}
    def setUp(self):
        super().setUp(self.PARAM_DIC)
        cmdline = """cat > nettle_test2.c <<EOF
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <nettle/des.h>

int main() {
    // 初始化DES上下文
    struct des_ctx ctx;
    // 设置DES密钥，长度为8字节
    uint8_t key[DES_KEY_SIZE] = {
        0x01, 0x23, 0x45, 0x67,
        0x89, 0xAB, 0xCD, 0xEF
    };
    // 待加密的明文，长度也为8字节
    uint8_t plaintext[DES_BLOCK_SIZE] = "NettleDE";
    // 存储加密后的密文
    uint8_t ciphertext[DES_BLOCK_SIZE];
    // 存储解密后的明文
    uint8_t decrypted[DES_BLOCK_SIZE];

    // 设置加密密钥
    des_set_key(&ctx, key);

    // 加密操作，只处理单个块
    des_encrypt(&ctx, sizeof(plaintext), ciphertext, plaintext);

    // 输出加密后的密文
    printf("加密后的密文: ");
    for (size_t i = 0; i < sizeof(ciphertext); i++) {
        printf("%02x ", ciphertext[i]);
    }
    printf("\\n");

    // 解密操作，只处理单个块
    des_decrypt(&ctx, sizeof(decrypted), decrypted, ciphertext);

    // 输出解密后的文本
    printf("解密后的文本: ");
    for (size_t i = 0; i < sizeof(decrypted); i++) {
        printf("%02x ", decrypted[i]);
    }
    printf("\\n");

    // 验证解密是否与原文匹配
    if (memcmp(plaintext, decrypted, sizeof(plaintext)) == 0) {
        printf("解密成功: 解密后的文本与原始明文匹配。\\n");
    } else {
        printf("解密失败: 解密后的文本与原始明文不匹配。\\n");
    }

    return 0;
}
EOF"""

        self.cmd(cmdline)
    
    def test(self):
        self.cmd('gcc -o nettle_test2 nettle_test2.c -lnettle')
        code, nettle_result = self.cmd("./nettle_test2")
        self.assertIn('解密成功: 解密后的文本与原始明文匹配', nettle_result)


    def tearDown(self):
        super().tearDown(self.PARAM_DIC)
        self.cmd('rm -rf nettle_test2 nettle_test2.c')
